package com.hawthorn.dic.service.impl;

import com.hawthorn.component.utils.common.StrMyUtil;
import com.hawthorn.component.utils.iassert.AssertMyUtil;
import com.hawthorn.dic.repository.SysDictMapper;
import com.hawthorn.dic.service.SysDictService;
import com.hawthorn.entity.dto.SysDictDTO;
import com.hawthorn.entity.dto.SysDivisionDTO;
import com.hawthorn.platform.context.ContextHolder;
import com.hawthorn.platform.redis.RedisMyClient;
import constant.DicCommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>todo 系统字典service</p>
 * @author: andyten@tom.com | xukaixing@hotmail.com
 * @created: 2021/11/29 5:01 PM
 * @version v1.0.2
 * @copyright: Copyright (c)  andyten
 */
@Service
@Slf4j
public class SysDictServiceImpl implements SysDictService
{
  @Autowired
  private SysDictMapper sysDictMapper;
  @Autowired
  private RedisMyClient redisMyClient;


  /**
   * <p>todo 生成全部字典</p>
   * @param:
   * @return: java.lang.String
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/9 5:56 PM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/9    andy.ten        v1.0.1             init
   */
  public String findDict()
  {
    // 绑定字典
    StringBuilder res = new StringBuilder("{");
    List<SysDictDTO> list = sysDictMapper.findDict();
    String curType, nextType = "";
    for (SysDictDTO sysDictDTO : list)
    {
      String node = "";
      curType = sysDictDTO.getType();
      if (!nextType.equals(curType))
      {
        if (res.length() > 1)
          res.append("]");
        nextType = sysDictDTO.getType();
        if (res.length() == 1)
          res.append("\"").append(sysDictDTO.getType()).append("\":");
        else
          res.append(",\"").append(sysDictDTO.getType()).append("\":");
        node += "[";
        node += "{\"c\":\"" + sysDictDTO.getDicCode() + "\",\"t\":\"" + sysDictDTO.getLabel() + "\",\"s\":\"" + sysDictDTO.getSpell() + "\",\"a\":\"" + sysDictDTO.getAspell() + "\",\"e\":\"" + "" + "\"}";
      } else
      {
        node += ",{\"c\":\"" + sysDictDTO.getDicCode() + "\",\"t\":\"" + sysDictDTO.getLabel() + "\",\"s\":\"" + sysDictDTO.getSpell() + "\",\"a\":\"" + sysDictDTO.getAspell() + "\",\"e\":\"" + "" + "\"}";
      }
      res.append(node);

    }
    res.append("]}");
    return res.toString();
  }

  public String findDictDivision()
  {
    // 绑定字典
    StringBuilder res = new StringBuilder("[");
    List<SysDivisionDTO> list = sysDictMapper.findDictDivision();
    String curType, nextType = "";
    String node = "";
    for (SysDivisionDTO sysDivisionDTO : list)
    {
      String sname = sysDivisionDTO.getSname();
      if (node.length() == 0)
        node = "{\"c\":\"" + sysDivisionDTO.getCode() + "\",\"t\":\"" + sysDivisionDTO.getSname() + "\",\"s\":\"" + sysDivisionDTO.getSpell() + "\"}";
      else
        node += ", {\"c\":\"" + sysDivisionDTO.getCode() + "\",\"t\":\"" + sysDivisionDTO.getSname() + "\",\"s\":\"" + sysDivisionDTO.getSpell() + "\"}";

    }
    res.append(node);
    res.append("]");
    return res.toString();
  }

  /**
   * <p>todo 获取表选格式字典</p>
   * @param: vparam
   * @return: java.lang.String
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/9 5:56 PM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/9    andy.ten        v1.0.1             init
   */
  @SuppressWarnings("rawtypes")
  public String findDictFromTable(String vparam, String query)
  {
    String userAccount = ContextHolder.getUserAccount();
    Map user = redisMyClient.getUserInfo(userAccount);
    if (vparam.startsWith("FUNC-"))
    {
      vparam = DicCommonConstant.getTableDic(user, vparam);
    }

    // String dbType = redisMyClient.getAppDBType();
    // if ("3".equals(dbType)) // mysql
    // {
    vparam = vparam.replaceAll("\\|\\|", "+");
    // }
    String strTabname;
    String strCodeCol;
    String strValueCol;
    ArrayList<String> fieldColumns = new ArrayList<>();
    String swhere = null;
    // String leafCol = null;
    // String parentCol = null;
    // String spell = null;
    // String aspell = null;

    String[] temps = vparam.split(":");
    AssertMyUtil.notNull(temps, "错误的参数设置，无法获取字典内容！");
    strTabname = temps[0];
    strCodeCol = temps[1];
    fieldColumns.add(strCodeCol);
    strValueCol = temps[2];
    if (temps.length >= 4)
      swhere = temps[3];
    // if (temps.length >= 5)
    //   leafCol = temps[4];
    // if (temps.length >= 6)
    //   parentCol = temps[5];
    // if (temps.length >= 7)
    //   spell = temps[6];
    // if (temps.length >= 8)
    //   aspell = temps[7];

    String sql = null;
    if (!StrMyUtil.isEmpty(strTabname)
        && !StrMyUtil.isEmpty(strCodeCol)
        && !StrMyUtil.isEmpty(strValueCol))
    {
      // 带有隐藏列
      if (strValueCol.indexOf("{") > 0)
      {
        String[] tt = strValueCol.split("\\{");
        String[] ttt = tt[1].split("}");
        String[] t = ttt[0].split(",");
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < t.length; i++)
        {
          if (i == 0)
            s = new StringBuilder("'" + t[i] + ":'#ifnull(" + t[i] + "#'null')");
          else
            s.append("#'#'#'").append(t[i]).append(":'").append("#ifnull(").append(t[i]).append("#'null')");
        }
        if (ttt.length == 1)
          s = new StringBuilder(tt[0] + "{" + s + "}");
        else
          s = new StringBuilder(tt[0] + "{" + s + "}" + ttt[1]);
        //s = s.replaceAll(",", ",',',");
        s = new StringBuilder(s.toString().replace("{", ",'{',"));
        s = new StringBuilder(s.toString().replace("}", ",'}'"));
        s = new StringBuilder(s.toString().replaceAll("@", ","));
        strValueCol = s.toString().replaceAll("#", ",");
      }
      if (strValueCol.indexOf("[") > 0)
      {
        String[] tt;
        tt = strValueCol.split("\\[");
        fieldColumns.add(tt[0]);
        String[] ttt;
        ttt = tt[1].split("]");
        String[] t = ttt[0].split(",");
        StringBuilder s;
        s = new StringBuilder();
        for (int i = 0; i < t.length; i++)
        {
          fieldColumns.add(t[i]);
          if (i == 0)
            s = new StringBuilder("'" + t[i] + ":'#ifnull(" + t[i] + "#'null')");
          else if (t[i].equals("'"))
            s.append("#").append(t[i]);
          else
            s.append("#'#'#'").append(t[i]).append(":'").append("#ifnull(").append(t[i]).append("#'null')");
        }
        s = new StringBuilder(tt[0] + "[" + s + "]");
        if (s.indexOf("{") == -1)
        {
          s = new StringBuilder(s.toString().replaceAll(",", ",',',"));
          s = new StringBuilder(s.toString().replaceAll("@", ","));
        }
        s = new StringBuilder(s.toString().replace("[", ",'[',"));
        s = new StringBuilder(s.toString().replace("]", ",']'"));
        if (ttt.length == 1)
          strValueCol = s.toString().replaceAll("#", ",");
        else
          strValueCol = s.toString().replaceAll("#", ",") + ttt[1];
        strValueCol = "concat(" + strValueCol + ",'')";
      } else
        fieldColumns.add(strValueCol);

      sql = "select " + strCodeCol + " as c," + strValueCol + " as t"
          + " from " +
          strTabname;
    } else AssertMyUtil.notNull(temps, "错误的参数设置，无法获取字典内容！");

    if (!StrMyUtil.isEmpty(swhere))
    {
      swhere = swhere.replaceAll("\\^", "'");
      sql += " where " + swhere;
    }
    // update: 表选字典增加过滤参数 2022-05-04
    String filterStr = "";
    if (!"".equals(query))
    {
      for (String field : fieldColumns)
      {
        if (filterStr.length() == 0)
          filterStr = " and (" + field + " like '%" + query + "%' ";
        else
          filterStr += "or " + field + " like '%" + query + "%' ";
      }
    }
    if (filterStr.length() > 0)
      filterStr += ")";
    sql += filterStr;
    // 增加sql记录限制
    sql += " limit 0, 200 ";
    log.info("@sql-T#:{}", sql);
    List<Map<String, Object>> result = sysDictMapper.findDictForTab(sql);
    StringBuilder res = new StringBuilder("[");
    for (Map<String, Object> map : result)
    {
      if (res.length() == 1)
        res.append("{");
      else
        res.append(",{");
      res.append("\"c\":\"").append(map.get("c")).append("\"");
      res.append(",\"t\":\"").append(map.get("t")).append("\"");
      res.append("}");
    }
    res.append("]");
    return res.toString();
  }

}
